<template>
    <div class="page-container">
        <div class="header">
            <h1>商店管理</h1>
            <div class="header-actions">
                <div class="search-container">
                    <input type="text" v-model="searchQuery" placeholder="搜索商店名称或地址...">
                </div>
                <button class="btn" @click="openAddStoreModal">添加商店</button>
            </div>
        </div>

        <div v-if="loading" class="loading-state">正在加载商店...</div>
        <div v-if="error" class="error-state">{{ error }}</div>

        <div v-if="stores" class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>商店</th>
                        <th>地址</th>
                        <th>评分</th>
                        <th>认证状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="store in filteredStores" :key="store.storeId">
                        <td>
                            <span>{{ store.storeId }}</span>
                        </td>
                        <td>
                            <img :src="store.coverImage || defaultLogo" alt="Store Logo" class="store-logo">
                            <span class="store-name">{{ store.name }}</span>
                        </td>
                        <td>{{ store.address }}</td>
                        <td>
                            <div class="rating">
                                <svg viewBox="0 0 24 24"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"></path></svg>
                                {{ store.rating !== undefined && store.rating !== null ? store.rating.toFixed(1) : '0.0' }}
                            </div>
                        </td>
                        <td>
                            <span class="status" :class="store.isCertified ? 'certified' : 'not-certified'">
                                {{ store.isCertified ? '已认证' : '未认证' }}
                            </span>
                        </td>
                        <td>
                            <a href="#" class="action-btn" @click.prevent="editStore(store)">编辑</a>
                            <a href="#" class="action-btn delete" @click.prevent="showDeleteConfirm(store)">删除</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 删除确认弹窗 -->
        <div v-if="deleteConfirmVisible" class="modal-overlay" @click.self="cancelDeleteConfirm">
            <div class="confirm-dialog">
                <div class="confirm-icon warning">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                    </svg>
                </div>
                <div class="confirm-content">
                    <h3>确认删除</h3>
                    <p>您确定要删除商店 <strong>{{ storeToDelete?.name }}</strong> 吗？此操作无法撤销。</p>
                </div>
                <div class="confirm-actions">
                    <button class="btn-cancel" @click="cancelDeleteConfirm">取消</button>
                    <button class="btn-confirm" @click="confirmDelete">确认删除</button>
                </div>
            </div>
        </div>

        <!-- Edit Store Modal -->
        <div v-if="isModalVisible" class="modal-overlay" @click.self="cancelEdit">
            <div class="modal-content">
                <h2>{{ isAddingStore ? '添加商店' : '编辑商店' }}</h2>
                <form @submit.prevent="isAddingStore ? addStore() : saveStore()">
                    <div class="form-group">
                        <label for="name">商店名称</label>
                        <input type="text" id="name" v-model="editableStore.name">
                    </div>
                    <div class="form-group">
                        <label for="description">描述</label>
                        <textarea id="description" v-model="editableStore.description"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="address">地址</label>
                        <input type="text" id="address" v-model="editableStore.address" @input="handleAddressInput">
                    </div>
                    <div class="form-group">
                        <label>地图选点 (点击地图选择位置)</label>
                        <div id="map-container" style="width: 100%; height: 400px; border: 1px solid #ddd; border-radius: 6px;"></div>
                    </div>
                    <div class="form-group">
                        <label for="phone">联系电话</label>
                        <input type="text" id="phone" v-model="editableStore.phone">
                    </div>
                    <div class="form-group">
                        <label for="businessHours">营业时间</label>
                        <div class="business-hours-container">
                            <!-- 工作日时间 -->
                            <div class="day-group">
                                <div class="day-selector">
                                    <label class="day-label">
                                        <input type="checkbox" v-model="weekdaysEnabled" @change="updateBusinessHours">
                                        <span class="day-text">周一至周五</span>
                                    </label>
                                </div>
                                <div class="time-picker-wrapper" :class="{ 'disabled': !weekdaysEnabled }">
                                    <input type="time" class="time-input" v-model="weekdaysStart" @change="updateBusinessHours" :disabled="!weekdaysEnabled">
                                    <span class="time-separator">至</span>
                                    <input type="time" class="time-input" v-model="weekdaysEnd" @change="updateBusinessHours" :disabled="!weekdaysEnabled">
                                </div>
                            </div>
                            
                            <!-- 周末时间 -->
                            <div class="day-group">
                                <div class="day-selector">
                                    <label class="day-label">
                                        <input type="checkbox" v-model="weekendsEnabled" @change="updateBusinessHours">
                                        <span class="day-text">周六至周日</span>
                                    </label>
                                </div>
                                <div class="time-picker-wrapper" :class="{ 'disabled': !weekendsEnabled }">
                                    <input type="time" class="time-input" v-model="weekendsStart" @change="updateBusinessHours" :disabled="!weekendsEnabled">
                                    <span class="time-separator">至</span>
                                    <input type="time" class="time-input" v-model="weekendsEnd" @change="updateBusinessHours" :disabled="!weekendsEnabled">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>封面图</label>
                        <div class="image-upload-centered">
                            <img :src="editableStore.coverImage || defaultLogo" alt="商店封面" class="image-preview">
                            <input type="file" :id="'coverImageUpload' + (editableStore.storeId || 'new')" @change="handleImageUpload($event, 'coverImage')" accept="image/*" style="display: none;">
                            <label :for="'coverImageUpload' + (editableStore.storeId || 'new')" class="btn btn-upload">
                                <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                                    <polyline points="17 8 12 3 7 8"></polyline>
                                    <line x1="12" y1="3" x2="12" y2="15"></line>
                                </svg>
                                选择图片
                            </label>
                        </div>
                    </div>
                    <div class="form-group form-group-inline">
                         <div>
                            <label for="longitude">经度</label>
                            <input type="number" id="longitude" v-model.number="editableStore.longitude" step="any" readonly>
                        </div>
                         <div>
                            <label for="latitude">纬度</label>
                            <input type="number" id="latitude" v-model.number="editableStore.latitude" step="any" readonly>
                        </div>
                    </div>

                    <!-- 商店标签 -->
                    <div class="form-group">
                        <label for="storeTag">商店标签</label>
                        <div class="tags-container">
                            <div class="tags-wrapper">
                                <div v-for="tag in storeTags" :key="tag.tagId" class="tag-item">
                                    <label class="tag-checkbox">
                                        <input type="checkbox" :value="tag.tagId" v-model="storeTags_selected">
                                        <span>{{ tag.name }}</span>
                                    </label>
                                </div>
                                <div v-if="storeTags.length === 0" class="no-tags">
                                    暂无可选标签
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 商店服务 -->
                    <div class="form-group">
                        <div class="services-header">
                            <h3>商店服务</h3>
                            <button type="button" class="btn btn-add-service" @click="addService">
                                <span>+</span> 添加服务
                            </button>
                        </div>
                        
                        <div class="services-container">
                            <div v-if="storeServices.length === 0" class="no-services">
                                <div class="empty-state">
                                    <svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2">
                                        <circle cx="12" cy="12" r="10"></circle>
                                        <line x1="12" y1="8" x2="12" y2="12"></line>
                                        <line x1="12" y1="16" x2="12.01" y2="16"></line>
                                    </svg>
                                    <p>暂无服务，点击"添加服务"添加第一个服务</p>
                                </div>
                            </div>
                            
                            <div v-for="(service, index) in storeServices" :key="index" class="service-item">
                                <div class="service-item-header">
                                    <h4>服务 #{{ index + 1 }}</h4>
                                    <button type="button" class="btn-icon" @click="removeService(index)" title="删除服务">
                                        <svg viewBox="0 0 24 24" width="18" height="18">
                                            <path fill="currentColor" d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z" />
                                        </svg>
                                    </button>
                                </div>
                                <div class="form-group">
                                    <label :for="'serviceName' + index">服务名称</label>
                                    <input type="text" :id="'serviceName' + index" v-model="service.name" placeholder="输入服务名称">
                                </div>
                                <div class="form-group">
                                    <label :for="'serviceDescription' + index">服务描述</label>
                                    <textarea :id="'serviceDescription' + index" v-model="service.description" placeholder="输入服务描述"></textarea>
                                </div>
                                <div class="form-group form-group-inline">
                                    <div>
                                        <label :for="'servicePrice' + index">价格</label>
                                        <div class="price-input-wrapper">
                                            <span class="price-prefix">¥</span>
                                            <input type="number" :id="'servicePrice' + index" v-model.number="service.price" step="0.01" min="0" placeholder="0.00">
                                        </div>
                                    </div>
                                    <div>
                                        <label :for="'serviceDuration' + index">时长（分钟）</label>
                                        <input type="number" :id="'serviceDuration' + index" v-model.number="service.duration" min="1" placeholder="30">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" @click="cancelEdit">取消</button>
                        <button type="submit" class="btn">{{ isAddingStore ? '添加' : '保存' }}</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 自定义提示弹窗 -->
        <div v-if="notification.show" class="notification-overlay" @click.self="closeNotification">
            <div class="notification" :class="notification.type">
                <div class="notification-icon">
                    <svg v-if="notification.type === 'success'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                        <path d="M22 4L12 14.01l-3-3"></path>
                    </svg>
                    <svg v-if="notification.type === 'error'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="12" cy="12" r="10"></circle>
                        <line x1="15" y1="9" x2="9" y2="15"></line>
                        <line x1="9" y1="9" x2="15" y2="15"></line>
                    </svg>
                </div>
                <div class="notification-content">
                    <h3>{{ notification.title }}</h3>
                    <p>{{ notification.message }}</p>
                </div>
                <button class="notification-close" @click="closeNotification">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue';
import { api } from '@/network/api';
import { ElTimeSelect } from 'element-plus';
import AMapLoader from '@amap/amap-jsapi-loader';

interface Store {
    storeId: number;
    name: string;
    logo?: string;
    coverImage?: string;
    description?: string;
    phone?: string;
    businessHours?: string;
    latitude?: number;
    longitude?: number;
    address: string;
    rating: number;
    reviewCount?: number;
    followerCount?: number;
    isCertified: number;
    certificationType?: string;
    createdAt?: string;
    services?: StoreService[];
    tags?: number[];
}

interface StoreService {
    serviceId?: number;
    storeId?: number;
    name: string;
    description: string;
    icon?: string;
    price: number;
    duration: number;
}

interface StoreTag {
    tagId: number;
    name: string;
}

interface Notification {
    show: boolean;
    type: 'success' | 'error';
    title: string;
    message: string;
    duration?: number;
}

const stores = ref<Store[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const defaultLogo = '/avatar/avatar.png';
const searchQuery = ref('');

const isModalVisible = ref(false);
const isAddingStore = ref(false);
const editableStore = ref<Partial<Store>>({});
const storeServices = ref<StoreService[]>([]);
const storeTags = ref<StoreTag[]>([]);
const storeTags_selected = ref<number[]>([]);

const filteredStores = computed(() => {
    if (!searchQuery.value) {
        return stores.value;
    }
    const lowerCaseQuery = searchQuery.value.toLowerCase();
    return stores.value.filter(store =>
        store.name.toLowerCase().includes(lowerCaseQuery) ||
        (store.address && store.address.toLowerCase().includes(lowerCaseQuery)) ||
        (store.description && store.description.toLowerCase().includes(lowerCaseQuery)) 
    );
});

// 地图相关
const map = ref<any>(null);
const marker = ref<any>(null);
const geocoder = ref<any>(null);
let searchTimeout: number | undefined = undefined;

const initMap = async () => {
    try {
        const AMap = await AMapLoader.load({
            key: '6753f35feab64d68da6a1e51fa2054f6',
            version: '2.0',
            plugins: ['AMap.Geocoder', 'AMap.ToolBar', 'AMap.Scale'],
        });

        const center = (editableStore.value.longitude && editableStore.value.latitude)
            ? [editableStore.value.longitude, editableStore.value.latitude]
            : [116.397428, 39.90923];

        map.value = new AMap.Map('map-container', {
            zoom: 14,
            center: center,
        });

        geocoder.value = new AMap.Geocoder();
        map.value.addControl(new AMap.ToolBar());
        map.value.addControl(new AMap.Scale());

        if (editableStore.value.longitude && editableStore.value.latitude) {
            updateMarkerPosition(new AMap.LngLat(editableStore.value.longitude, editableStore.value.latitude));
        }

        map.value.on('click', (e: any) => {
            const { lng, lat } = e.lnglat;
            editableStore.value.longitude = lng;
            editableStore.value.latitude = lat;
            updateMarkerPosition(e.lnglat);
            getAddressFromCoordinates(lng, lat);
        });

    } catch (e) {
        console.error('地图加载失败:', e);
        showNotification('error', '地图加载失败', '请检查网络连接或联系管理员。');
    }
};

const updateMarkerPosition = (lngLat: any) => {
    if (!map.value) return;
    if (marker.value) {
        marker.value.setPosition(lngLat);
    } else {
        // AMap is loaded on window, but typescript might not know
        marker.value = new (window as any).AMap.Marker({
            position: lngLat,
            map: map.value,
        });
    }
    map.value.setCenter(lngLat);
};

const getAddressFromCoordinates = async (lng: number, lat: number) => {
    try {
        const key = '6753f35feab64d68da6a1e51fa2054f6';
        const url = `https://restapi.amap.com/v3/geocode/regeo?key=${key}&location=${lng},${lat}`;
        const response = await fetch(url);
        const data = await response.json();
        if (data.status === '1' && data.regeocode) {
            editableStore.value.address = data.regeocode.formatted_address;
        } else {
            console.error('逆地理编码失败:', data.info);
            showNotification('error', '地址解析失败', '无法根据坐标获取地址信息');
        }
    } catch (error) {
        console.error('逆地理编码请求失败:', error);
        showNotification('error', '网络错误', '地址解析服务请求失败');
    }
};

const searchLocationByAddress = () => {
    if (geocoder.value && editableStore.value.address) {
        geocoder.value.getLocation(editableStore.value.address, (status: string, result: any) => {
            if (status === 'complete' && result.geocodes.length) {
                const { lng, lat } = result.geocodes[0].location;
                editableStore.value.longitude = lng;
                editableStore.value.latitude = lat;
                updateMarkerPosition(new (window as any).AMap.LngLat(lng, lat));
            } else {
                 showNotification('error', '地址解析失败', '无法找到该地址对应的位置');
            }
        });
    }
};

const handleAddressInput = () => {
    clearTimeout(searchTimeout);
    searchTimeout = window.setTimeout(() => {
        searchLocationByAddress();
    }, 800); // 800ms debounce
};

const destroyMap = () => {
    if (map.value) {
        map.value.destroy();
        map.value = null;
        marker.value = null;
        geocoder.value = null;
    }
};

watch(isModalVisible, (isVisible) => {
    if (isVisible) {
        nextTick(() => {
            initMap();
        });
    } else {
        destroyMap();
    }
});

// 提示信息
const notification = ref<Notification>({
    show: false,
    type: 'success',
    title: '',
    message: '',
    duration: 3000
});

// 显示提示信息
const showNotification = (type: 'success' | 'error', title: string, message: string) => {
    notification.value = {
        show: true,
        type,
        title,
        message,
        duration: 3000
    };

    // 自动关闭
    setTimeout(() => {
        closeNotification();
    }, notification.value.duration);
};

// 关闭提示信息
const closeNotification = () => {
    notification.value.show = false;
};

// 营业时间选择器
const weekdaysEnabled = ref(false);
const weekendsEnabled = ref(false);
const weekdaysStart = ref('09:00');
const weekdaysEnd = ref('22:00');
const weekendsStart = ref('10:00');
const weekendsEnd = ref('22:00');

// 格式化营业时间预览
const formattedBusinessHours = computed(() => {
    let formatted = '';
    
    if (weekdaysEnabled.value) {
        formatted += `1-5:${weekdaysStart.value}-${weekdaysEnd.value}`;
    }
    
    if (weekendsEnabled.value) {
        if (formatted) formatted += ',';
        formatted += `6-7:${weekendsStart.value}-${weekendsEnd.value}`;
    }
    
    return formatted || '未设置营业时间';
});

// 更新营业时间
const updateBusinessHours = () => {
    editableStore.value.businessHours = formattedBusinessHours.value !== '未设置营业时间' 
        ? formattedBusinessHours.value 
        : '';
};

// 解析营业时间
const parseBusinessHours = (hours: string | undefined) => {
    if (!hours) {
        weekdaysEnabled.value = false;
        weekendsEnabled.value = false;
        return;
    }
    
    // 重置状态
    weekdaysEnabled.value = false;
    weekendsEnabled.value = false;
    
    // 分割不同天组的时间
    const timeGroups = hours.split(',');
    
    timeGroups.forEach(group => {
        // 解析天和时间，例如 "1-5:9:00-22:00"
        const match = group.match(/(\d+-\d+):(\d+:\d+)-(\d+:\d+)/);
        
        if (match) {
            const [_, days, startTime, endTime] = match;
            
            // 处理工作日
            if (days === '1-5') {
                weekdaysEnabled.value = true;
                weekdaysStart.value = startTime;
                weekdaysEnd.value = endTime;
            }
            // 处理周末
            else if (days === '6-7') {
                weekendsEnabled.value = true;
                weekendsStart.value = startTime;
                weekendsEnd.value = endTime;
            }
        }
    });
};

const fetchStoreTags = async () => {
    try {
        const response = await api.getStoreTags();
        storeTags.value = response.data.data || [];
    } catch (err) {
        console.error("获取商店标签失败:", err);
    }
};

const fetchStores = async () => {
    try {
        loading.value = true;
        const response = await api.getStoreList();
        // 处理后端返回的StoresInfo数组结构
        if (response && response.data) {
            // 后端返回的是StoresInfo数组，每个StoresInfo包含stores、storeServicesList和tag
            // 我们需要提取每个StoresInfo中的stores对象作为商店数据
            stores.value = response.data.map((storeInfo: any) => {
                // 确保stores对象存在
                if (storeInfo && storeInfo.stores) {
                    return {
                        ...storeInfo.stores,
                        // 可以选择性地将服务和标签信息也附加到商店对象上
                        services: storeInfo.storeServicesList || [],
                        tags: storeInfo.tag || []
                    };
                }
                return null;
            }).filter((store: any) => store !== null); // 过滤掉null值
        } else {
            stores.value = [];
            console.error("获取商店列表失败: 返回数据格式不正确", response);
        }
        error.value = null;
    } catch (err) {
        console.error("获取商店列表失败:", err);
        error.value = '商店列表加载失败，请稍后重试。';
        stores.value = [];
    } finally {
        loading.value = false;
    }
};

const handleImageUpload = (event: Event, field: 'coverImage') => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files[0]) {
        const file = target.files[0];
        const reader = new FileReader();
        reader.onload = (e) => {
            if (e.target?.result) {
                editableStore.value[field] = e.target.result as string;
            }
        };
        reader.readAsDataURL(file);
    }
};

const addService = () => {
    storeServices.value.push({
        name: '',
        description: '',
        price: 0,
        duration: 30,
        icon: ''
    });
};

const removeService = (index: number) => {
    storeServices.value.splice(index, 1);
};

const openAddStoreModal = () => {
    isAddingStore.value = true;
    editableStore.value = {
        name: '',
        address: '',
        description: '',
        isCertified: 1,
        certificationType: '',
        logo: '',
        rating: 0,
        reviewCount: 0,
        followerCount: 0
    };
    storeServices.value = [];
    
    // 重置营业时间选择器
    weekdaysEnabled.value = false;
    weekendsEnabled.value = false;
    weekdaysStart.value = '09:00';
    weekdaysEnd.value = '22:00';
    weekendsStart.value = '10:00';
    weekendsEnd.value = '22:00';
    
    // 清空已选标签
    storeTags_selected.value = [];
    
    isModalVisible.value = true;
};

const editStore = async (store: Store) => {
    isAddingStore.value = false;
    editableStore.value = { ...store };
    
    // 解析营业时间
    parseBusinessHours(store.businessHours);
    
    try {
        // 获取商店服务
        if (store.storeId) {
            // 如果store对象已经包含services属性，则直接使用
            if (store.services && Array.isArray(store.services)) {
                storeServices.value = [...store.services];
                console.log('使用已附加的服务数据:', storeServices.value);
            } else {
                // 否则通过API获取
                const response = await api.getStoreServices(store.storeId);
                storeServices.value = response.data.data || [];
                console.log('通过API获取服务数据:', storeServices.value);
            }
            
            // 如果store对象已经包含tags属性，则直接使用
            if (store.tags && Array.isArray(store.tags)) {
                storeTags_selected.value = [...store.tags];
                console.log('使用已附加的标签数据:', storeTags_selected.value);
            } else {
                // 否则通过API获取
                try {
                    const tagResponse = await api.getStoreTagsById(store.storeId);
                    if (tagResponse.data && Array.isArray(tagResponse.data)) {
                        storeTags_selected.value = tagResponse.data.map(tag => tag.tagId);
                    } else {
                        storeTags_selected.value = [];
                    }
                    console.log('通过API获取标签数据:', storeTags_selected.value);
                } catch (tagErr) {
                    console.error("获取商店标签失败:", tagErr);
                    storeTags_selected.value = [];
                }
            }
        } else {
            storeServices.value = [];
            storeTags_selected.value = [];
        }
    } catch (err) {
        console.error("获取商店数据失败:", err);
        storeServices.value = [];
        storeTags_selected.value = [];
    }
    
    isModalVisible.value = true;
};

const saveStore = async () => {
    if (!editableStore.value.storeId) return;
    try {
        // 构建更新数据
        const storeInfo = {
            stores: editableStore.value,
            storeServicesList: storeServices.value.map(service => ({
                ...service,
                icon: ''
            })),
            tag: storeTags_selected.value // 使用多选标签数组
        };
        
        await api.updateStore(storeInfo);
        
        // 先关闭弹窗，避免重叠
        isModalVisible.value = false;
        
        showNotification('success', '操作成功', '商店更新成功！');
        await fetchStores();
    } catch (err) {
        console.error("更新商店失败:", err);
        showNotification('error', '操作失败', '商店更新失败！请稍后重试。');
    }
};

const addStore = async () => {
    try {
        const storeInfo = {
            stores: {
                ...editableStore.value,
                isCertified: 1, // 确保isCertified为1
                logo: '', // 确保logo为空字符串
                certificationType: '' // 确保certificationType为空字符串
            },
            storeServicesList: storeServices.value.map(service => ({
                ...service,
                icon: '' // 确保所有服务的图标都为空字符串
            })),
            tag: storeTags_selected.value // 使用多选标签数组
        };
        await api.addStore(storeInfo);
        
        // 先关闭确认弹窗，避免重叠
        isModalVisible.value = false;
        
        showNotification('success', '操作成功', '商店添加成功！');
        await fetchStores();
    } catch (err) {
        console.error("添加商店失败:", err);
        showNotification('error', '操作失败', '商店添加失败！请稍后重试。');
    }
};

const cancelEdit = () => {
    isModalVisible.value = false;
};

// 删除确认相关数据
const deleteConfirmVisible = ref(false);
const storeToDelete = ref<Store | null>(null);

// 显示删除确认弹窗
const showDeleteConfirm = (store: Store) => {
    storeToDelete.value = store;
    deleteConfirmVisible.value = true;
};

// 取消删除
const cancelDeleteConfirm = () => {
    deleteConfirmVisible.value = false;
    storeToDelete.value = null;
};

// 确认删除
const confirmDelete = async () => {
    if (!storeToDelete.value) return;
    
    try {
        const storeId = storeToDelete.value.storeId;
        const storeName = storeToDelete.value.name;
        
        // 先关闭确认弹窗，避免重叠
        deleteConfirmVisible.value = false;
        
        await api.delStore(storeId);
        
        // 显示成功消息，包含商店名称
        showNotification('success', '删除成功', `商店 ${storeName} 已删除`);
        
        // 重新加载商店列表
        await fetchStores();
    } catch (err) {
        console.error('删除商店失败:', err);
        showNotification('error', '删除失败', '删除商店时发生错误，请稍后重试');
    } finally {
        // 清空选中的商店
        storeToDelete.value = null;
    }
};

onMounted(() => {
    fetchStores();
    fetchStoreTags();
});
</script>

<style scoped>
.page-container {
    padding: 30px;
}
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
}
.header h1 {
    font-size: 2em;
    margin: 0;
}
.header-actions {
    display: flex;
    align-items: center;
    gap: 20px;
}
.search-container input {
    width: 300px;
    padding: 10px 15px;
    font-size: 1em;
    border-radius: 6px;
    border: 1px solid #ddd;
    transition: box-shadow 0.2s, border-color 0.2s;
}
.search-container input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}
.btn {
    background-color: #3498db;
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    text-decoration: none;
    font-size: 1em;
    transition: background-color 0.3s;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.btn:hover {
    background-color: #2980b9;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
.table-container {
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    margin-top: 20px;
}
table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}
th, td {
    padding: 20px 24px;
    text-align: left;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}
th {
    background-color: #f8f9fa;
    font-weight: 600;
    font-size: 1.2em;
    color: #555;
}
td {
    font-size: 1.2em;
}
tr:last-child td {
    border-bottom: none;
}
.store-logo {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 50%;
    vertical-align: middle;
    margin-right: 20px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.store-name {
    font-weight: 500;
}
.status {
    padding: 6px 12px;
    border-radius: 12px;
    font-size: 0.9em;
    font-weight: 500;
    display: inline-block;
}
.status.certified {
    background-color: #e8f5e9;
    color: #2e7d32;
}
.status.not-certified {
    background-color: #fff3e0;
    color: #f57c00;
}
.rating {
    display: flex;
    align-items: center;
    color: #f5c518;
    font-weight: 600;
}
.rating svg {
    width: 20px;
    height: 20px;
    fill: currentColor;
    margin-right: 8px;
}
.action-btn {
    color: #3498db;
    text-decoration: none;
    margin-right: 20px;
    font-weight: 500;
    padding: 6px 12px;
    border-radius: 4px;
    transition: all 0.2s;
}
.action-btn:hover {
    text-decoration: none;
    background-color: rgba(52, 152, 219, 0.1);
}
.action-btn.delete {
    color: #e74c3c;
}
.action-btn.delete:hover {
    background-color: rgba(231, 76, 60, 0.1);
}
.loading-state, .error-state {
    padding: 40px;
    text-align: center;
    color: #666;

}

/* Modal Styles */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    padding: 40px;
    border-radius: 12px;
    width: 90%;
    max-width: 800px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.2);
    max-height: 85vh;
    overflow-y: auto;
}

.modal-content h2 {
    margin-top: 0;
    margin-bottom: 30px;
    font-size: 1.8em;
    color: #333;
}

.form-group {
    margin-bottom: 25px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 1.1em;
    color: #444;
}

.form-group input[type="text"],
.form-group input[type="number"],
.form-group input[type="time"],
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 6px;
    box-sizing: border-box;
    font-size: 1.05em;
    transition: all 0.3s;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.15);
    outline: none;
}

.form-group textarea {
    min-height: 100px;
    resize: vertical;
}

.form-group-inline {
    display: flex;
    gap: 25px;
    align-items: flex-start;
}

.form-group-inline > div {
    flex: 1;
}

/* 营业时间选择器样式 */
.business-hours-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 30px;
    background-color: #f9f9f9;
}

.day-group {
    display: flex;
    align-items: center;
    gap: 30px;
    padding: 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    transition: all 0.2s;
}

.day-group:hover {
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.day-selector {
    width: 140px;
}

.day-label {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
}

.day-label input[type="checkbox"] {
    width: 18px;
    height: 18px;
    cursor: pointer;
}

.day-text {
    font-weight: 600;
    color: #333;
    font-size: 1.05em;
}

.time-picker-wrapper {
    display: flex;
    align-items: center;
    flex: 1;
    background: #fff;
    border-radius: 6px;
    padding: 0 10px;
    border: 1px solid #e0e0e0;
    transition: all 0.2s;
}

.time-picker-wrapper:hover:not(.disabled) {
    border-color: #3498db;
}

.time-picker-wrapper.disabled {
    opacity: 0.5;
    background-color: #f5f5f5;
}

.time-input {
    flex: 1;
    border: none;
    padding: 12px;
    border-radius: 6px;
    background: transparent;
    color: #333;
    font-size: 1.05em;
}

.time-input:focus {
    outline: none;
}

.time-input:disabled {
    background-color: transparent;
    cursor: not-allowed;
}

.time-separator {
    margin: 0 15px;
    color: #555;
    font-weight: bold;
    font-size: 1.05em;
}

/* 新增封面图上传居中样式 */
.image-upload-centered {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 30px;
    width: 100%;
    padding: 40px 0;
    border: 2px dashed #ccd0d5;
    border-radius: 12px;
    background-color: #f9f9fa;
    transition: all 0.3s;
}

.image-upload-centered:hover {
    border-color: #3498db;
    background-color: #f0f7fc;
}

.image-preview {
    width: 180px;
    height: 180px;
    border-radius: 10px;
    object-fit: cover;
    border: 1px solid #ddd;
    box-shadow: 0 5px 15px rgba(0,0,0,0.15);
}

.btn-upload {
    display: flex;
    align-items: center;
    gap: 10px;
    background-color: #fff;
    color: #3498db;
    border: 1px solid #3498db;
    padding: 12px 20px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 1.05em;
}

.btn-upload:hover {
    background-color: #3498db;
    color: #fff;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

/* 商店标签选择器样式 */
.tags-container {
    display: flex;
    justify-content: center;
    padding: 12px 15px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    background-color: #f9f9f9;
    min-height: 50px;
}

.tags-wrapper {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    gap: 8px;
    max-width: 90%;
}

.tag-item {
    background-color: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 16px;
    transition: all 0.2s;
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
    display: inline-flex;
    margin-bottom: 3px;
}

.tag-item:hover {
    border-color: #3498db;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transform: translateY(-1px);
}

.tag-checkbox {
    display: flex;
    align-items: center;
    padding: 3px 10px;
    cursor: pointer;
}

.tag-checkbox input[type="checkbox"] {
    margin-right: 6px;
    cursor: pointer;
    width: 14px;
    height: 14px;
}

.tag-checkbox span {
    font-size: 0.9em;
    color: #444;
    white-space: nowrap;
}

.no-tags {
    width: 100%;
    text-align: center;
    color: #888;
    padding: 10px;
    font-style: italic;
}

/* 商店服务样式增强 */
.services-container {
    margin-top: 25px;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
    color: #888;
    background-color: #f9f9f9;
    border: 1px dashed #ddd;
    border-radius: 10px;
}

.empty-state svg {
    margin-bottom: 20px;
    color: #3498db;
    width: 50px;
    height: 50px;
}

.empty-state p {
    font-size: 1.2em;
    margin: 0;
}

.no-services {
    padding: 30px 0;
}

.service-item {
    background-color: #fff;
    border-radius: 10px;
    padding: 30px;
    margin-bottom: 30px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    border: 1px solid #e9ecef;
    position: relative;
    transition: all 0.3s;
}

.service-item:hover {
    box-shadow: 0 8px 20px rgba(0,0,0,0.1);
    transform: translateY(-3px);
}

.service-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
}

.service-item-header h4 {
    margin: 0;
    font-size: 1.3em;
    color: #3498db;
}

.btn-icon {
    background: none;
    border: none;
    color: #dc3545;
    cursor: pointer;
    padding: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s;
}

.btn-icon:hover {
    background-color: rgba(220, 53, 69, 0.1);
    transform: scale(1.2);
}

.services-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.services-header h3 {
    margin: 0;
    font-size: 1.4em;
    color: #333;
    font-weight: 600;
}

.btn-add-service {
    background-color: #28a745;
    color: white;
    border: none;
    border-radius: 6px;
    padding: 12px 20px;
    font-size: 1.05em;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s;
}

.btn-add-service:hover {
    background-color: #218838;
    transform: translateY(-3px);
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.btn-add-service span {
    font-size: 1.3em;
    font-weight: bold;
}

/* 价格输入框样式 */
.price-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.price-prefix {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: #555;
    font-weight: 600;
    font-size: 1.1em;
}

.price-input-wrapper input {
    padding-left: 35px !important;
}

.modal-actions {
    margin-top: 35px;
    text-align: right;
    display: flex;
    justify-content: flex-end;
    gap: 15px;
}

.btn-secondary {
    background-color: #6c757d;
    font-size: 1.05em;
    padding: 12px 24px;
    border-radius: 6px;
    border: none;
    color: white;
    cursor: pointer;
    transition: all 0.3s;
}

.btn-secondary:hover {
    background-color: #5a6268;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

/* 提示弹窗样式 */
.notification-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1100;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.notification {
    display: flex;
    max-width: 450px;
    width: 90%;
    background: white;
    border-radius: 10px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.2);
    padding: 24px;
    position: relative;
    animation: slideIn 0.3s ease;
    border-left: 5px solid;
}

@keyframes slideIn {
    from { transform: translateY(-30px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.notification.success {
    border-left-color: #10b981;
}

.notification.error {
    border-left-color: #ef4444;
}

.notification-icon {
    flex: 0 0 50px;
    height: 50px;
    margin-right: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
}

.notification.success .notification-icon {
    color: #10b981;
}

.notification.error .notification-icon {
    color: #ef4444;
}

.notification-icon svg {
    width: 36px;
    height: 36px;
}

.notification-content {
    flex: 1;
}

.notification-content h3 {
    margin: 0 0 10px;
    font-size: 1.3em;
    color: #333;
}

.notification-content p {
    margin: 0;
    color: #555;
    font-size: 1.05em;
}

.notification-close {
    position: absolute;
    top: 15px;
    right: 15px;
    width: 30px;
    height: 30px;
    border: none;
    background: transparent;
    cursor: pointer;
    color: #888;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.notification-close:hover {
    color: #333;
    transform: scale(1.1);
}

.notification-close svg {
    width: 20px;
    height: 20px;
}

/* 确认删除弹窗样式 */
.confirm-dialog {
    background: white;
    border-radius: 10px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
    width: 90%;
    max-width: 450px;
    padding: 30px;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    animation: bounceIn 0.4s ease;
}

@keyframes bounceIn {
    0% { transform: scale(0.8); opacity: 0; }
    70% { transform: scale(1.05); }
    100% { transform: scale(1); opacity: 1; }
}

.confirm-icon {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 25px;
}

.confirm-icon.warning {
    background-color: #fff3e6;
    color: #ff9800;
}

.confirm-icon svg {
    width: 40px;
    height: 40px;
}

.confirm-content {
    margin-bottom: 30px;
    width: 100%;
}

.confirm-content h3 {
    font-size: 1.6em;
    margin: 0 0 15px;
    color: #333;
    font-weight: 600;
}

.confirm-content p {
    margin: 0;
    color: #666;
    line-height: 1.6;
    font-size: 1.1em;
}

.confirm-content strong {
    color: #333;
    font-weight: 600;
}

.confirm-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    width: 100%;
}

.btn-cancel,
.btn-confirm {
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 1.05em;
    font-weight: 500;
    cursor: pointer;
    border: none;
    transition: all 0.3s;
    min-width: 120px;
}

.btn-cancel {
    background-color: #f1f3f5;
    color: #495057;
}

.btn-cancel:hover {
    background-color: #e9ecef;
    transform: translateY(-2px);
    box-shadow: 0 3px 6px rgba(0,0,0,0.1);
}

.btn-confirm {
    background-color: #dc3545;
    color: white;
}

.btn-confirm:hover {
    background-color: #c82333;
    transform: translateY(-2px);
    box-shadow: 0 3px 6px rgba(0,0,0,0.1);
}
</style> 